package javaNIO1.channel;

import com.alibaba.spring.util.ObjectUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Objects;

/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/7/20 16:55
 */
public class serverSocketChannel {
    private final static int PORT = 13;
    private final static String GETTING = "Hello! I must bo going!";
    public static void main(String[] args) {
        ByteBuffer result = ByteBuffer.wrap(GETTING.getBytes());
        // ServerSocketChannel 可以使用静态工厂open 打开一个并创建
        try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();){

            /**
             *  可以使用ServerSocket 调用accept()，但是总是阻塞 并返回Socket  对象
             */


            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞模式
            serverSocketChannel.configureBlocking(false);

            while(true){
                System.out.println("Waiting for connections");
                // 监听链接等待链接， 并且能在非阻塞模式下运行，在没有连接进入时 总是立即返回null
                SocketChannel accept = serverSocketChannel.accept();

                if(Objects.isNull(accept)){
                    Thread.sleep(20000);
                }else {
                    System.out.println("Incoming connection from:" + accept.socket().getRemoteSocketAddress());
                    result.rewind();
                    accept.write(result);
                    accept.close();
                }
            }
        }catch (IOException e){e.printStackTrace();} catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
